package com.xiaoming.backend.dao.impl;

import com.xiaoming.backend.dao.IUserDao;
import com.xiaoming.backend.dao.mapper.UserPOMapper;
import com.xiaoming.backend.dto.request.RegisterRequest;
import com.xiaoming.backend.entity.db.example.UserPOExample;
import com.xiaoming.backend.entity.db.po.UserPO;
import com.xiaoming.backend.entity.orm.User;
import com.xiaoming.backend.result.exception.AppErrorException;
import com.xiaoming.backend.result.exception.error.AppError;
import com.xiaoming.backend.util.EntityUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserDao implements IUserDao {
    private final UserPOMapper userPOMapper;
    private final PasswordEncoder passwordEncoder;


    @Override
    public List<UserPO> getUserInfoForUserName(String userNmae) {
        UserPOExample e = new UserPOExample();
        e.createCriteria().andUserNameEqualTo(userNmae);
        return userPOMapper.selectByExample(e);
    }

    @Override
    public User insertUserForUserInfo(RegisterRequest request) {
        UserPO user = EntityUtil.registerRequestTOUserPO(request);
        try {
            user.setCrtdDate(new Date());
            int s = userPOMapper.insert(user);
            if (s == 0){
                throw new AppErrorException(AppError.USER_INSERT_ERROR);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            throw new AppErrorException(AppError.USER_INSERT_ERROR);
        }

        return EntityUtil.userPOTOUser(user);
    }
}
